package com.it.system.eduorderservice.listener;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.system.eduorderservice.config.TimeoutOrderMQConfig;
import com.it.system.eduorderservice.entity.UserCourseOrder;
import com.it.system.eduorderservice.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel; // 修正后的导入
import java.util.logging.Logger;

@Component
@Slf4j
public class TimeoutOrderListener {

    private Logger logger = Logger.getLogger(TimeoutOrderListener.class.getName());

    @Autowired
    private TimeoutOrderMQConfig timeoutOrderMQConfig;

    @Autowired
    private OrderService orderService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = TimeoutOrderMQConfig.DEADLETTER_ORDER_QUEUE,durable = "true"),
            exchange = @Exchange(value = TimeoutOrderMQConfig.DEADLETTER_ORDER_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = {TimeoutOrderMQConfig.DEADLETTER_ORDER_QUEUE_KEY}
    ))
    public  void handleTimeoutOrder(String tradeNo, Channel channel, Message message){
        logger.info("订单超时，订单号："+tradeNo);
        try{
            //查询订单
            UserCourseOrder order=
                    orderService.getOne(new QueryWrapper<UserCourseOrder>().lambda().eq(UserCourseOrder::getTradeNo,tradeNo));

            //如果没有支付
            if (order.getStatus() == 0) {

                order.setStatus(2L);
                orderService.update(order,new QueryWrapper<UserCourseOrder>().lambda().eq(UserCourseOrder::getTradeNo,tradeNo));
                log.info("订单超时，订单号："+tradeNo);
            }
            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            log.error("订单超时，订单号："+tradeNo);
        }


    }

}
